package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Business;
import cn.hist.hfp.service.BusinessService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/business")
public class BusinessController {

    private final
    BusinessService businessService;

    private final
    Authentication authentication;

    private final
    MyResponse<Business> myResponse;

    @Autowired
    public BusinessController(BusinessService businessService, Authentication authentication, MyResponse<Business> myResponse) {
        this.businessService = businessService;
        this.authentication = authentication;
        this.myResponse = myResponse;
    }

    @PostMapping
    public ResponseEntity<Business> create(@RequestBody Business business, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return myResponse.response(201, authentication.refreshToken(token), businessService.create(business));
    }

    @GetMapping("/{id}")
    public Business findOne(@PathVariable int id) {
        return businessService.findOne(id);
    }

    @GetMapping
    public List<BusinessVO> findAll() {
        return businessService.findAll();
    }

    @PutMapping
    public ResponseEntity<Business> update(@RequestBody Business business, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return myResponse.response(200, authentication.refreshToken(token), businessService.update(business));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        MyResponse<Integer> myResponse = new MyResponse<>();
        return myResponse.response(200, authentication.refreshToken(token), businessService.delete(id));
    }
}
